package com.servlet;

import com.dao.UserUtils;
import com.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/find")
public class FindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;UTF-8");
        StringBuffer sb = new StringBuffer();
        List<User> userList = UserUtils.findAllUser();

        sb.append("<a href=\"/web04/user/add.html\">添加</a>\n" +
                "<table border=\"1px\">\n" +
                "  <tr>\n" +
                "    <th>用户名</th>\n" +
                "    <th>年龄</th>\n" +
                "    <th>性别</th>\n" +
                "    <th>地址</th>\n" +
                "    <th>操作</th>\n" +
                "    <th>修改</th>\n" +
                "  </tr>");

        for (User user : userList) {
          sb.append("  <tr>\n" +
                  "    <td>"+user.getName()+"</td>\n" +
                  "    <td>"+user.getAge()+"</td>\n" +
                  "    <td>"+user.getSex()+"</td>\n" +
                  "    <td>"+user.getAddress()+"</td>\n" +
                  "    <td><a href=\"/web04/user/delete?username="+user.getName()+"\">删除</a> </td>\n" +
                  "    <td><a href=\"/web04/user/update.html\">修改</a> </td>\n" +
                  "  </tr>");
        }
        sb.append("</table>");

        resp.getWriter().write(sb.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
